//
//  NSDate+Extension.swift
//  weibo1
//
//  Created by changhongliang on 2017/7/27.
//  Copyright © 2017年 richinfo. All rights reserved.
//

import UIKit

extension NSDate{
    
    class func dateWithString(string:String) -> NSDate?{
        //1.将微博的发布时间转化为NSDate
        //1.1创建时间格式化对象
        let formatter = DateFormatter()
        //1.2初始化时间格式化对象
        formatter.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        formatter.locale = Locale(identifier: "en")
        //1.3将发布微博的时间字符串转化为NSDate
       return formatter.date(from: string)! as NSDate
    }

    /// 返回格式化之后的时间字符串
    var desc: String
    {
        let formatter = DateFormatter()
        //日历
        let calendar = NSCalendar.current
        
        //发布时间: 2014-11-12 00:00:00
        //当前时间: 2015-10-11 00:00:00
        if calendar.isDateInToday(self as Date) {
            //2.1获取当前时间和发布时间之间的时间差
            let timeInterval = Int(Date().timeIntervalSince(self as Date))
            
            
            ///注意点:对于xcode8来说如果timeInterval <60 这样写会报错,注意要在"<"和 60 之间要加空格
            if timeInterval < 60 {
                return "刚刚"
            }else if timeInterval < 60*60
            {
                return "\(timeInterval/60)分钟前"
            }else if timeInterval < 60*60*24
            {
                return "\(timeInterval/(60*60))小时前"
                
            }
        }
        
        //昨天
        var formatterStr = "HH:mm"
        let unitFlags = Set<Calendar.Component>([.day, .month, .year, .hour])
        let comps = calendar.dateComponents(unitFlags, from: self as Date,  to: NSDate() as Date)
        if calendar.isDateInYesterday(self as Date) {
            formatterStr = "昨天" + formatterStr
        }else if comps.year! < 1{
            //一年之内
            formatterStr = "MM-dd " + formatterStr
        }else {
            //更早时间
            formatterStr = "yy-MM-dd " + formatterStr
            
        }
        formatter.dateFormat = formatterStr
        return formatter.string(from:self as Date)
    }






}
